<template>
  <div v-if="error" class="error-boundary">
    <a-result
      status="error"
      title="页面出错了"
      :sub-title="error.message"
    >
      <template #extra>
        <div class="error-actions">
          <a-space>
            <a-button type="primary" @click="handleRetry">
              <template #icon><ReloadOutlined /></template>
              重试
            </a-button>
            <a-button @click="handleBack">
              <template #icon><RollbackOutlined /></template>
              返回
            </a-button>
          </a-space>
          <div class="error-details">
            <a-collapse>
              <a-collapse-panel key="1" header="错误详情">
                <pre>{{ error.stack }}</pre>
              </a-collapse-panel>
            </a-collapse>
          </div>
        </div>
      </template>
    </a-result>
  </div>
  <slot v-else></slot>
</template>

<script setup>
import { ref, onErrorCaptured, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ReloadOutlined, RollbackOutlined } from '@ant-design/icons-vue'

const router = useRouter()
const route = useRoute()
const error = ref(null)

// 监听路由变化，重置错误状态
watch(
  () => route.path,
  () => {
    error.value = null
  }
)

onErrorCaptured((err) => {
  error.value = err
  return false // 阻止错误继续传播
})

const handleRetry = () => {
  error.value = null
  // 使用 router.go(0) 替代 window.location.reload()
  // 这样可以保持 Vue Router 的状态
  router.go(0)
}

const handleBack = () => {
  error.value = null
  router.back()
}
</script>

<style scoped>
.error-boundary {
  padding: 24px;
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.error-actions {
  display: flex;
  flex-direction: column;
  gap: 24px;
  align-items: center;
}

.error-details {
  margin-top: 24px;
  max-width: 800px;
  width: 100%;
}

.error-details pre {
  background: #f5f5f5;
  padding: 16px;
  border-radius: var(--border-radius-base);
  overflow: auto;
  font-family: monospace;
  font-size: 12px;
  line-height: 1.5;
}

[data-theme='dark'] .error-details pre {
  background: #1f1f1f;
}
</style> 